package cmd

import (
	"fmt"
	"log"

	"github.com/spf13/cobra"
	"gorm.io/driver/mysql"
	"gorm.io/driver/postgres"
	"gorm.io/driver/sqlite"
	"gorm.io/gen"
	"gorm.io/gorm"
	"pets.ser163.cn/config"
)

var genCmd = &cobra.Command{
	Use:   "gen",
	Short: "Run generate models",
	Run: func(cmd *cobra.Command, args []string) {
		log.Println("Running generate ...")
		// 数据库生成模型
		genModels()
	},
}

func init() {
	rootCmd.AddCommand(genCmd)
}

func genModels() {
	var db *gorm.DB

	var err error
	dbConfig := config.ConfigInstance.Database

	// 配置数据库连接
	switch dbConfig.Type {
	case "sqlite":
		db, err = gorm.Open(sqlite.Open(dbConfig.SQLite.Path), &gorm.Config{})
	case "mysql":
		dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
			dbConfig.MySQL.User, dbConfig.MySQL.Password, dbConfig.MySQL.Host, dbConfig.MySQL.Port, dbConfig.MySQL.Name)
		db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	case "postgres":
		dsn := fmt.Sprintf("host=%s user=%s password=%s dbname=%s port=%d sslmode=%s",
			dbConfig.Postgres.Host, dbConfig.Postgres.User, dbConfig.Postgres.Password, dbConfig.Postgres.Name, dbConfig.Postgres.Port, dbConfig.Postgres.SSLMode)
		db, err = gorm.Open(postgres.Open(dsn), &gorm.Config{})
	default:
		log.Fatalf("Unsupported database type: %s", dbConfig.Type)
	}

	if err != nil {
		panic("failed to connect database")
	}

	// 创建生成器实例
	g := gen.NewGenerator(gen.Config{
		OutPath: "query", // 生成的文件存放路径
	})
	g.UseDB(db)

	// 自动生成代码
	g.ApplyBasic(g.GenerateAllTable()...)
	g.Execute()
}
